import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_member/pages/login/login_page.dart';
import 'package:flutter_member/widget/custom_appbar.dart';
import 'package:flutter_member/widget/radio/we_switch.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:parse_server_sdk/parse_server_sdk.dart';
import 'package:path_provider/path_provider.dart';
import 'package:toast/toast.dart';

import 'about_rulin.dart';

class SettingsPage extends StatefulWidget {
  @override
  _SettingsPageState createState() => _SettingsPageState();
}

//退出登錄
Future<void> _logout() async {
  final ParseUser user = await ParseUser.currentUser() as ParseUser;
  user.logout();

  print('登錄用戶已退出！');
}

class _SettingsPageState extends State<SettingsPage> {
  String _cacheSizeStr = '0.0M';

  ///加载缓存
  Future<Null> loadCache() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
      tempDir.list(followLinks: false, recursive: true).listen((file) {
        //打印每个缓存文件的路径
        print(file.path);
      });
      print('临时目录大小: ' + value.toString());
      setState(() {
        _cacheSizeStr = _renderSize(value);
      });
    } catch (err) {
      print(err);
    }
  }

  /// 递归方式 计算文件的大小
  Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
        int length = await file.length();
        return double.parse(length.toString());
      }
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        double total = 0;
        if (children != null)
          for (final FileSystemEntity child in children)
            total += await _getTotalSizeOfFilesInDir(child);
        return total;
      }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }

  void _clearCache() async {
    //此处展示加载loading
    try {
      Directory tempDir = await getTemporaryDirectory();
      //删除缓存目录
      await delDir(tempDir);
      await loadCache();
      print('清理缓存成功');
    } catch (e) {
      print(e);
      print('清除缓存失败');
    } finally {
      //此处隐藏加载loading
    }
  }

  ///递归方式删除目录
  Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
        final List<FileSystemEntity> children = file.listSync();
        for (final FileSystemEntity child in children) {
          await delDir(child);
        }
      }
      await file.delete();
    } catch (e) {
      print(e);
    }
  }

  ///格式化文件大小
  _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()..add('B')..add('K')..add('M')..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }
// 弹窗
  void showCupertinoAlertDialog() {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return CupertinoAlertDialog(
            title: Text("請確認是否清除緩存"),
            content: Column(
              children: <Widget>[
                SizedBox(
                  height: 10,
                ),
                Align(
                  child: Text("可能會包含一些圖片"),
                  alignment: Alignment(0, 0),
                ),
              ],
            ),
            actions: <Widget>[
              CupertinoDialogAction(
                child: Text("取消"),
                onPressed: () {
                  Navigator.pop(context);
                  print("取消");
                },
              ),
              CupertinoDialogAction(
                child: Text("确定"),
                onPressed: () {
                  Navigator.pop(context);
                  _clearCache();
                },
              ),
            ],
          );
        });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadCache();
  }

  @override
  Widget build(BuildContext context) {
    return CustomAppBar(
      title: '設置',
      hight: 79,
      upperColor: 0xff2D7FC7,
      lowerColor: 0xffE5EEF6,
      body: Container(
        alignment: Alignment.topCenter,
        child: _setSettings(),
      ),
    );
  }

  ///  設置模塊方型，
  Widget _setSettings() {
    return Container(
      height: ScreenUtil().setHeight(289),
      width: ScreenUtil().setWidth(335),
      margin: EdgeInsets.only(top: 40),
      child: Stack(
        children: [
          Container(
            decoration: BoxDecoration(
                color: Color(0xffE5EEF6),
                borderRadius: BorderRadius.all(Radius.circular(18)),
                boxShadow: [
                  BoxShadow(
                    color: Color(0xffedf2f9),
                    blurRadius: 5, //阴影范围
                    spreadRadius: 6, //阴影浓度
                  ),
                ]),
          ),
          Container(
            margin: EdgeInsets.only(top: 5),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(18)),
            ),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                _settingItem(
                    title: '通知',
                    actions: WeSwitch(
                      selColor: Color(0xff6DD400),
                      unSelCor: Color(0xff8890A6),
                      onChange: (v) {},
                    )),
                _settingItem(
                    title: '關於儒林教育',
                    actions: Icon(
                      Icons.keyboard_arrow_right,
                      color: Color(0xffBABAC4),
                      size: 32,
                    ),
                    onTop: () => Navigator.push(context, MaterialPageRoute(
                        builder: (context) =>AboutRulin()))),
                _settingItem(
                    title: '用戶協議',
                    actions: Icon(
                      Icons.keyboard_arrow_right,
                      color: Color(0xffBABAC4),
                      size: 32,
                    )),
                _settingItem(
                    title: '清除緩存',
                    actions: _clearCacheWidget(size: _cacheSizeStr),
                    onTop: () => showCupertinoAlertDialog()),
                Container(
                  padding: EdgeInsets.only(left: 20, right: 20, top: 15),
                  child: Divider(
                    height: 1,
                    color: Color(0xffBDC0C8),
                  ),
                ),
                _logoutButton(title: '退出登錄')
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 設置子組件
  Widget _settingItem({String title, Widget actions, VoidCallback onTop}) {
    return InkWell(
      onTap: onTop,
      child: Container(
        margin: EdgeInsets.all(10),
        padding: EdgeInsets.only(left: 30, right: 20, top: 10),
        child: Row(
          children: [
            Expanded(
              child: Text(
                title,
                style: TextStyle(
                    color: Color(0xff7B7B7B),
                    fontSize: ScreenUtil().setSp(14),
                    fontWeight: FontWeight.w400,
                    fontFamily: 'SemiBold'),
              ),
            ),
            actions
          ],
        ),
      ),
    );
  }

  ///  清除緩存右側組件
  Widget _clearCacheWidget({String size}) {
    return Row(
      children: [
        Text(
          size,
          style: TextStyle(
              color: Color(0xff154D7C),
              fontSize: ScreenUtil().setSp(15),
              fontFamily: 'SemiBold',
              fontWeight: FontWeight.w500),
        ),
        ImageIcon(
          AssetImage('images/delete_small.png'),
          size: ScreenUtil().setSp(12),
          color: Color(0xff7B7B7B),
        )
      ],
    );
  }

  Widget _logoutButton({String title}) {
    return InkWell(
      onTap: () {
        _logout();
        Navigator.push(context, MaterialPageRoute(builder: (BuildContext context){
          return LoginPage();
        }));
      },
      child: Container(
        alignment: Alignment.center,
        height: ScreenUtil().setHeight(51),
        child: Text(
          title,
          style: TextStyle(
              color: Color(0xffE02020),
              fontSize: ScreenUtil().setSp(16),
              fontWeight: FontWeight.w400,
              fontFamily: 'SemiBold'),
        ),
      ),
    );
  }
}
